package com.zby.business.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zby.business.R;
import com.zby.business.activity.Detail;
import com.zby.business.net.MyAsyncTask;
import com.zby.business.util.Util;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

/**
 * Created by BY on 2016/4/14.
 */
public class ManageFragment extends Fragment {
    private View view;
    private ListView listView;
    private ArrayList detailId, name, introduce, price, discount, sale, picture;
    private LayoutInflater inflater;
    private MyAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.manage, null);
        init();
        return view;
    }

    private void init() {
        inflater = LayoutInflater.from(getContext());
        detailId = new ArrayList();
        name = new ArrayList();
        introduce = new ArrayList();
        price = new ArrayList();
        discount = new ArrayList();
        sale = new ArrayList();
        picture = new ArrayList();
        listView = (ListView) view.findViewById(R.id.manage);
        MyAsyncTask task = new MyAsyncTask();
        try {
            final String s = task.execute("getDetails").get();
            System.out.println(s);
            JSONObject object = new JSONObject(s);
            JSONArray details = object.getJSONArray("details");
            for (int i = 0; i < details.length(); i++) {
                JSONObject detail = (JSONObject) details.get(i);
                detailId.add(detail.get("commodityDetailId"));
                name.add(detail.get("commodityBrand"));
                introduce.add(detail.get("commodityIntroduce"));
                price.add(detail.get("commodityPrice"));
                discount.add(detail.get("discount"));
                sale.add(detail.get("commoditySale"));
                picture.add(detail.get("commodityPicture"));
            }
            adapter = new MyAdapter();
            listView.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return name.size();
        }

        @Override
        public Object getItem(int position) {
            return name.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = inflater.inflate(R.layout.manage_list_item, null);
            TextView brand = (TextView) convertView.findViewById(R.id.name);
            Button modify = (Button) convertView.findViewById(R.id.modify);
            Button delete = (Button) convertView.findViewById(R.id.delete);
            brand.setText(name.get(position) + "");
            modify.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
                    View view = inflater.inflate(R.layout.modify, null);
                    final EditText mName = (EditText) view.findViewById(R.id.name);
                    final EditText mPrice = (EditText) view.findViewById(R.id.price);
                    final EditText mIntroduce = (EditText) view.findViewById(R.id.introduce);
                    final EditText mDiscount = (EditText) view.findViewById(R.id.discount);
                    Button confirmButton = (Button) view.findViewById(R.id.confiemModify);
                    mName.setText(name.get(position) + "");
                    mPrice.setText(price.get(position) + "");
                    mDiscount.setText(discount.get(position) + "");
                    mIntroduce.setText(introduce.get(position) + "");
                    confirmButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AsyncHttpClient client = new AsyncHttpClient();
                            RequestParams params = new RequestParams();
                            params.put("name", mName.getText().toString());
                            params.put("introduce", mIntroduce.getText().toString());
                            params.put("price", mPrice.getText().toString());
                            params.put("discount", mDiscount.getText().toString());
                            params.put("detailId", detailId.get(position));
                            client.post(Util.BASE_URL + "modifyCommodity", params, new AsyncHttpResponseHandler() {
                                @Override
                                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                                    System.out.println(SUCCESS_MESSAGE);
                                }

                                @Override
                                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                                    System.out.println("fail");
                                }
                            });
                            alertDialog.dismiss();
                        }
                    });
                    alertDialog.setView(view);
                    alertDialog.show();
                }
            });
            delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getContext(),AlertDialog.THEME_HOLO_LIGHT);
                    builder.setMessage("删除商品？");
                    builder.setPositiveButton("确认删除", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            MyAsyncTask asyncTask = new MyAsyncTask();
                            try {
                                asyncTask.execute("deleteCommodity?detailId=" + detailId.get(position)).get();
                                detailId.remove(position);
                                name.remove(position);
                                introduce.remove(position);
                                price.remove(position);
                                discount.remove(position);
                                sale.remove(position);
                                picture.remove(position);
                                adapter.notifyDataSetChanged();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    builder.show();

                }
            });
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity().getApplicationContext(), Detail.class);
//                intent.putExtra("name", )
                    Bundle bundle = new Bundle();
                    bundle.putString("introduce", introduce.get(position) + "");
                    bundle.putString("price", price.get(position) + "");
                    bundle.putString("sale", sale.get(position) + "");
                    bundle.putString("commodityId", detailId.get(position) + "");
                    bundle.putString("url", picture.get(position) + "");
                    intent.putExtra("bundle", bundle);
                    startActivity(intent);
                }
            });
            return convertView;
        }
    }
}
